<template>
  <div class="output-statistics">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="时间">
          <el-date-picker
            v-model="searchForm.startTime"
            type="date"
            placeholder="开始时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 150px"
          />
          <span class="date-separator">至</span>
          <el-date-picker
            v-model="searchForm.endTime"
            type="date"
            placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 150px"
          />
        </el-form-item>
        
        <el-form-item label="工单号">
          <el-input
            v-model="searchForm.workOrderNumber"
            placeholder="工单号"
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="产品名称">
          <el-input
            v-model="searchForm.productName"
            placeholder="产品名称"
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="产品编号">
          <el-input
            v-model="searchForm.productNumber"
            placeholder="产品编号"
            style="width: 200px"
          />
        </el-form-item>
      </el-form>
      
      <div class="button-group">
        <el-button type="primary" @click="handleSearch" :icon="Search">
          查询
        </el-button>
        <el-button @click="handleReset" :icon="Refresh">
          重置
        </el-button>
        <el-button type="success" @click="handleExport" :icon="Download">
          导出
        </el-button>
        <el-button :icon="Grid" class="view-toggle-btn">
          <el-icon><Grid /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <h3 class="table-title">产量统计</h3>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%; flex: 1;"
        border
        stripe
        @selection-change="handleSelectionChange"
        :max-height="400"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column label="统计ID" prop="statisticsId" width="100" align="center" />
        
        <el-table-column label="报工日期" width="150">
          <template #default="scope">
            {{ formatDate(scope.row.reportingDate) }}
          </template>
        </el-table-column>
        
        <el-table-column label="工单号" prop="workOrderNumber" width="150" />
        
        <el-table-column label="产品编号" prop="productNumber" width="150" />
        
        <el-table-column label="产品名称" prop="productName" width="150" />
        
        <el-table-column label="产品规格" prop="productSpecification" width="150" />
        
        <el-table-column label="计划数量" prop="workOrderPlanQuantity" width="150" align="center" />
        
        <el-table-column label="实际产量" prop="productQuantity" width="150" align="center" />
        
        
        
        <el-table-column label="单位" prop="unit" width="150" align="center" />
        
        
      </el-table>

      <!-- 合计行 -->
      <div class="total-row">
        <span class="total-label">合计：</span>
                 <span class="total-value">
           计划数量: {{ totalPlanQuantity }} | 
           实际产量: {{ totalActualQuantity }} | 
           记录数: {{ tableData.length }}
         </span>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download, Grid } from '@element-plus/icons-vue'
import { 
  getAllOutputStatistics, 
  searchOutputStatistics, 
  exportOutputStatistics,
  type OutputStatistics,
  type ApiResponse,
  type SearchParams
} from '@/api/outputStatistics'
import { exportToCSVOutput, exportToExcelOutput } from '@/utils/excelExport'

// 搜索表单数据
const searchForm = reactive({
  startTime: '',
  endTime: '',
  workOrderNumber: '',
  productName: '',
  productNumber: ''
})

// 表格数据
const tableData = ref<OutputStatistics[]>([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 30,
  total: 0
})

// 选中的行
const selectedRows = ref<OutputStatistics[]>([])

// 加载状态
const loading = ref(false)

// 计算合计数量
const totalPlanQuantity = computed(() => {
  return tableData.value.reduce((sum, item) => sum + item.workOrderPlanQuantity, 0)
})

const totalActualQuantity = computed(() => {
  return tableData.value.reduce((sum, item) => sum + item.productQuantity, 0)
})



// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toISOString().split('T')[0]
}





// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const response = await getAllOutputStatistics()
    
    if (response.data.code === 200) {
      tableData.value = response.data.data
      pagination.total = response.data.data.length
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error(response.data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params: SearchParams = {}
    if (searchForm.startTime) params.startTime = searchForm.startTime
    if (searchForm.endTime) params.endTime = searchForm.endTime
    if (searchForm.workOrderNumber) params.workOrderNumber = searchForm.workOrderNumber
    if (searchForm.productName) params.productName = searchForm.productName
    if (searchForm.productNumber) params.productNumber = searchForm.productNumber

    const response = await searchOutputStatistics(params)
    
    if (response.data.code === 200) {
      tableData.value = response.data.data
      pagination.total = response.data.data.length
      ElMessage.success('查询成功')
    } else {
      ElMessage.error(response.data.msg || '查询失败')
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 重置处理
const handleReset = () => {
  searchForm.startTime = ''
  searchForm.endTime = ''
  searchForm.workOrderNumber = ''
  searchForm.productName = ''
  searchForm.productNumber = ''
  fetchData() // 重新加载所有数据
  ElMessage.info('已重置搜索条件')
}

// 导出处理
const handleExport = async () => {
  try {
    // 优先尝试后端导出
    const params: SearchParams = {}
    if (searchForm.startTime) params.startTime = searchForm.startTime
    if (searchForm.endTime) params.endTime = searchForm.endTime
    if (searchForm.workOrderNumber) params.workOrderNumber = searchForm.workOrderNumber
    if (searchForm.productName) params.productName = searchForm.productName
    if (searchForm.productNumber) params.productNumber = searchForm.productNumber

    try {
      const response = await exportOutputStatistics(params)
      
      // 检查响应类型
      const contentType = response.headers['content-type']
      let fileName = `产量统计_${new Date().toISOString().split('T')[0]}`
      
      // 根据响应类型设置文件扩展名
      if (contentType && contentType.includes('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) {
        fileName += '.xlsx'
      } else if (contentType && contentType.includes('application/vnd.ms-excel')) {
        fileName += '.xls'
      } else {
        fileName += '.xlsx' // 默认Excel格式
      }
      
      // 创建下载链接
      const blob = new Blob([response.data], { 
        type: contentType || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = fileName
      link.style.display = 'none'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      ElMessage.success('后端导出成功')
      return
    } catch (backendError) {
      console.warn('后端导出失败，使用前端导出:', backendError)
    }
    
    // 后端导出失败，使用前端导出当前数据
    if (tableData.value.length === 0) {
      ElMessage.warning('没有数据可导出')
      return
    }
    
    const fileName = `产量统计_${new Date().toISOString().split('T')[0]}`
    
    // 尝试使用XLSX库导出Excel
    const excelSuccess = await exportToExcelOutput(tableData.value, fileName)
    
    if (excelSuccess) {
      ElMessage.success('前端Excel导出成功')
    } else {
      // 回退到CSV格式
      exportToCSVOutput(tableData.value, fileName)
      ElMessage.success('前端CSV导出成功（可用Excel打开）')
    }
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  }
}

// 选择变化处理
const handleSelectionChange = (selection: OutputStatistics[]) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  // 重新加载数据
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  // 重新加载数据
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.output-statistics {
  padding: 20px;
  background: #fff;
  height: calc(100vh - 100px);
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.search-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 15px;
}

.date-separator {
  margin: 0 10px;
  color: #666;
}

.button-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.view-toggle-btn {
  margin-left: auto;
}

.table-section {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-title {
  padding: 15px 20px;
  margin: 0;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.total-row {
  padding: 15px 20px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  gap: 10px;
}

.total-label {
  font-weight: 600;
  color: #333;
}

.total-value {
  font-weight: 600;
  color: #409eff;
}

.pagination-section {
  padding: 20px;
  display: flex;
  justify-content: flex-end;
  background: #fff;
  border-top: 1px solid #e9ecef;
  flex-shrink: 0;
}

/* 自定义滚动条样式 */
.output-statistics::-webkit-scrollbar {
  width: 8px;
}

.output-statistics::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.output-statistics::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.output-statistics::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .output-statistics {
    height: calc(100vh - 80px);
    padding: 15px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .button-group {
    flex-wrap: wrap;
  }
  
  .view-toggle-btn {
    margin-left: 0;
  }
}
</style>
